package com.yinhai.model.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

import com.yinhai.model.UserUserContact;

public class GroupSearchTreeManager {

	private static GroupSearchTreeManager INSTANCE = null;
	protected TreeMap<String, UserUserContact> map;
		
	private GroupSearchTreeManager() {
		map = new TreeMap<String, UserUserContact>(new CheckCodeComparator());	
	}
	
	public static GroupSearchTreeManager CreateInstance() {
		if(INSTANCE == null)
			INSTANCE = new GroupSearchTreeManager();
		return INSTANCE;
	}

	public static GroupSearchTreeManager GetInstance() {
		return INSTANCE;
	}
	
	public Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException();
	}
	
	private int getIndexCount(String src, int len) {
		int k = 0, i = 0;
		while(i < len) {
			if(src.charAt(i) == ',') {
				++k;
			} else {
				++i;
			}
		}
		return k;
	}
	
	public List<UserUserContact> GetCheckList(String key) {
		List<UserUserContact> listData = new ArrayList<UserUserContact>();
		
		if(key == null || (key.length() <= 3 && key.charAt(0) == '1')) {
			return listData;
		}
		
		NavigableMap<String, UserUserContact> tailMap = map.tailMap(key, true); 
		for(Map.Entry<String, UserUserContact> entry : tailMap.entrySet()) {
			if(entry.getKey().startsWith(key)) {
				switch(entry.getKey().charAt(entry.getKey().length() - 1)) {
				case '#':
					entry.getValue().setMatchType("2");
					entry.getValue().setEnd(key.length() - 1);
					break;
				case '%':
					entry.getValue().setMatchType("3");
					entry.getValue().setEnd(key.length() - 1);
					break;
				case '&':
					entry.getValue().setMatchType("1");
					entry.getValue().setEnd(key.length() - 1);
					break;
				case '*':
					entry.getValue().setMatchType("1");
					entry.getValue().setEnd(getIndexCount(entry.getValue().getFullpysep(), key.length()));
					break;
				case '+':
					entry.getValue().setMatchType("1");
					entry.getValue().setEnd(key.length() - 1);
					break;
				case '<':
					entry.getValue().setMatchType("1");
					entry.getValue().setEnd(key.length() - 1);
					break;
				case '>':
					entry.getValue().setMatchType("1");
					entry.getValue().setEnd(getIndexCount(entry.getValue().getFullpysep(), key.length()));
					break;					
				}
				listData.add(entry.getValue());
			} else {
				break;
			}
		}
		
		return listData;
	}

}
